# from django.shortcuts import render

from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import IsAuthenticated
import json
from django.http import JsonResponse, HttpResponseNotAllowed, HttpResponse, HttpResponseBadRequest

from .models import *

# GetSorts 取分类(衣服、化妆品等)
@api_view(['GET'])
@permission_classes([IsAuthenticated])
def GetSorts(request):
    user = request.user  # 获取已验证的用户对象
    sorts = Sort.objects.filter(user=user)
    if sorts is not None:
        sorts_data = [
            {
                'sort_id': sort.sort_id,
                'sort_name': sort.sort_name
            } 
            for sort in sorts
        ]
        return JsonResponse({'data': sorts_data},status=200)
    return JsonResponse({'message': 'Sort data NotFound.'}, status=404)

# GetCategories 获取衣服的属性分类，如种类、颜色、位置
@api_view(['GET'])
@permission_classes([IsAuthenticated])
def GetCategories(request):
    SortID = request.GET.get('sort_id')
    # 根据上级ID过滤查询结果
    categories = Category.objects.filter(sort_id=SortID)
    if categories is not None:
        # 提取所需的字段
        categories_data = [
            {
                'category_id': category.category_id,
                'category_name': category.category_name
            } 
            for category in categories
        ]
        return JsonResponse({'data': categories_data}, status=200)
    return JsonResponse({'message': 'Category data NotFound'}, status=404)

# UpdateCategory 更新衣服的属性分类，如种类、颜色、位置
@api_view(['POST'])
@permission_classes([IsAuthenticated])
def UpdateCategory(request):
    try:
        # 获取请求体的原始数据
        body = request.body.decode('utf-8')
        data = json.loads(body)
    except:
        return JsonResponse({'message': 'request body is required.'}, status=400)
    # 获取参数
    CategoryName = data.get('category_name')
    SortID = data.get('sort_id')  #新增使用
    CategoryID = data.get('category_id')     #修改使用
    if CategoryName==None:
        return JsonResponse({'message': 'CategoryName is required.'}, status=400)
    try:
        if CategoryID != None:
            # 查找具有匹配 category_id 的 Category 对象
            category = Category.objects.get(category_id=CategoryID)
            category.category_name = CategoryName
            category.save()
            return JsonResponse({'message': 'Category updated successfully.'}, status=200)
        elif SortID != None:
            # 在 SortID 下创建一个新的 Category 对象
            sort = Sort.objects.get(sort_id=SortID)
            category = Category.objects.create(sort=sort, category_name=CategoryName)
            category.save()
            return JsonResponse({'message': 'Category added successfully.'}, status=200)
        else:
            # 如果既没有 CategoryId 也没有 SortID，则返回错误响应
            return JsonResponse({'message': 'CategoryId or SortID is required.'}, status=400)
    except Category.DoesNotExist:
        return JsonResponse({'message': 'Category not found.'}, status=404)

# DelCategory 删除衣服的属性分类，如种类、颜色、位置
@api_view(['DELETE'])
@permission_classes([IsAuthenticated])
def DelCategory(request):
    try:
        # 获取请求体的原始数据
        body = request.body.decode('utf-8')
        data = json.loads(body)
    except:
        return JsonResponse({'message': 'request body is required.'}, status=400)
    # 获取参数
    CategoryId = data.get('category_id') 
    try:
        if CategoryId != None:
            # 查找具有匹配 category_id 的 Category 对象
            category = Category.objects.get(category_id=CategoryId)
            category.delete()  # 删除 Category 对象
            return JsonResponse({'message': f"Category '{category.category_name}' deleted successfully."}, status=200)
        else:
            # 如果没有 CategoryId ，则返回错误响应
            return JsonResponse({'message': 'CategoryId is required.'}, status=400)
    except Category.DoesNotExist:
        return JsonResponse({'message': 'Category not found.'}, status=404)

# Property 属性，传入属性分类ID，如衣服种类，获取种类属性，如上衣(T恤、卫衣、衬衫)、下装(牛仔裤、运动裤)
@api_view(['GET'])
@permission_classes([IsAuthenticated])
def GetProperties(request):
    CategoryId = request.GET.get('category_id')
    try:
        category = Category.objects.get(category_id=CategoryId)  
        properties = Property.objects.filter(category_id=category)  # 获取该 Category 下的所有 Property 对象

        # 创建属性字典以及父属性ID字典
        property_dict = {}
        parent_dict = {}
        for property in properties:
            property_data = {
                'property_id': property.property_id,
                'property_name': property.property_name,
                'children': []
            }
            property_dict[property.property_id] = property_data
            if property.super_property_id:
                parent_dict[property.property_id] = property.super_property.property_id

        # 构建树形结构的 JSON 格式
        property_list = []
        for property_id, property_data in property_dict.items():
            parent_id = parent_dict.get(property_id)
            if parent_id:
                parent_property = property_dict.get(parent_id)
                if parent_property:
                    parent_property['children'].append(property_data)
                else:
                    property_list.append(property_data)
            else:
                property_list.append(property_data)

        return JsonResponse({'data': property_list}, status=200)
    except Category.DoesNotExist:
        return JsonResponse({'message': 'Category not found.'}, status=404)

# UpdateProperty 新增/修改种类属性，如上衣(T恤、卫衣、衬衫)、下装(牛仔裤、运动裤)等值
@api_view(['POST'])
@permission_classes([IsAuthenticated])
def UpdateProperty(request):
    try:
        # 获取请求体的原始数据
        body = request.body.decode('utf-8')
        data = json.loads(body)
    except:
        return JsonResponse({'message': 'request body is required.'}, status=400)
    # 获取参数
    CategoryId = data.get('category_id')
    PropertyName = data.get('property_name')
    PropertyId = data.get('property_id')     #修改使用
    SuperID = data.get('super_id')  #新增使用或不使用
    if PropertyName==None:
        return JsonResponse({'message': 'PropertyName is required.'}, status=400)
    try:
        if PropertyId != None:
            # 修改
            CurrProperty = Property.objects.get(property_id=PropertyId)
            CurrProperty.property_name = PropertyName
            CurrProperty.save()
            return JsonResponse({'message': 'Property updated successfully.'}, status=200)
        else: 
            category = Category.objects.get(category_id=CategoryId)
            if SuperID!=None:
                # 新增子类
                super_property = Property.objects.get(property_id=SuperID)
                NewProperty = Property.objects.create(super_property=super_property, 
                category = category, property_name=PropertyName)
            else:
                NewProperty = Property.objects.create(category = category, property_name=PropertyName)
            NewProperty.save()
            return JsonResponse({'message': 'Property added successfully.'}, status=200)
    except Property.DoesNotExist:
        return JsonResponse({'message': 'Property not found.'}, status=404)

# DelProperty 删除种类属性，如上衣(T恤、卫衣、衬衫)、下装(牛仔裤、运动裤)等值
@api_view(['DELETE'])
@permission_classes([IsAuthenticated])
def DelProperty(request):
    try:
        # 获取请求体的原始数据
        body = request.body.decode('utf-8')
        data = json.loads(body)
    except:
        return JsonResponse({'message': 'request body is required.'}, status=400)
    # 获取参数
    PropertyId = data.get('property_id') 
    try:
        if PropertyId != None:
            # 查找具有匹配 property_id 的 Property 对象
            currProperty = Property.objects.get(property_id=PropertyId)
            currProperty.delete()  # 删除 Property 对象
            return JsonResponse({'message': f"Property '{currProperty.property_name}' deleted successfully."}, status=200)
        else:
            # 如果没有 PropertyId ，则返回错误响应
            return JsonResponse({'message': 'PropertyId is required.'}, status=400)
    except Property.DoesNotExist:
        return JsonResponse({'message': 'Property not found.'}, status=404)

# Object 属性，传入分类ID，如衣服，获取物品，如短袖1
@api_view(['GET'])
@permission_classes([IsAuthenticated])
def GetObjects(request):
    SortID = request.GET.get('sort_id')
    try:
        sort = Sort.objects.get(sort_id=SortID) 
        objects = Object.objects.filter(sort=sort)

        object_list = []
        for oneObject in objects:
            object_data = {
                'object_id': oneObject.object_id,
                'object_name': oneObject.object_name,
                'image': oneObject.image.url if oneObject.image else None
            }
            object_list.append(object_data)

        return JsonResponse({'data': object_list}, status=200)
    except Sort.DoesNotExist:
        return JsonResponse({'message': 'Sort not found.'}, status=404)

# Object 详细属性，传入衣服ID
@api_view(['GET'])
@permission_classes([IsAuthenticated])
def GetObjectDetail(request):
    ObjectID = request.GET.get('object_id')
    try:
        cObject = Object.objects.get(object_id=ObjectID)
        object_data = {
            'object_id': cObject.object_id,
            'object_name': cObject.object_name,
            'purchase_date': cObject.purchase_date.strftime('%Y-%m-%d'),
            'price': cObject.price,
            'image': cObject.image.url if cObject.image else None,
            'remark': cObject.remark,
            'properties': []
        }
        # 获取当前物品所有的属性
        objectProperties = ObjectProperty.objects.filter(object=cObject)
        property_values = objectProperties.values(
            'property__category', 'property__category__category_name', 
            'property', 'property__property_name')
        
        for property in property_values:
            property_data = {
                "category_id": property['property__category'],
                "category_name": property['property__category__category_name'],
                "property_id": property['property'],
                "property_name": property['property__property_name']
            }
            object_data['properties'].append(property_data)
        return JsonResponse({'data': object_data}, status=200)
    except Object.DoesNotExist:
        return JsonResponse({'message': 'Object not found.'}, status=404)

# UpdateObject 新增/修改物品基本信息
@api_view(['POST'])
@permission_classes([IsAuthenticated])
def UpdateObject(request):
    try:
        # 获取请求体的原始数据
        body = request.body.decode('utf-8')
        data = json.loads(body)
    except:
        return JsonResponse({'message': 'request body is required.'}, status=400)
    # 获取参数
    SortID = data.get('sort_id')
    ObjectName = data.get('object_name')
    PurchaseDate = data.get('purchase_date')
    ObjectPrice = data.get('price')
    ObjectRemark = data.get('remark')
    ObjectId = data.get('object_id')     #修改使用
    
    properties = data.get('properties')
    try:
        if ObjectId != None:
            # 修改
            CurrObject = Object.objects.get(object_id=ObjectId)
            CurrObject.object_name = ObjectName
            CurrObject.purchase_date = PurchaseDate
            CurrObject.price = ObjectPrice
            CurrObject.remark = ObjectRemark
            CurrObject.save()
            
            # 删除当前物品的所有属性
            ObjectProperty.objects.filter(object=CurrObject).delete()
            # 添加新的属性
            for property in properties:
                CurrProperty = Property.objects.get(property_id=property['property_id'])
                # 创建新的ObjectProperty对象
                property_obj = ObjectProperty(
                    object=CurrObject,
                    property=CurrProperty
                )
                property_obj.save()
            return JsonResponse({'message': 'Object updated successfully.'}, status=200)
        else: 
            if SortID == None:
                return JsonResponse({'message': 'SortID is required.'}, status=400)
            sort = Sort.objects.get(sort_id=SortID)
            NewObject = Object.objects.create(sort=sort, object_name=ObjectName,
                purchase_date=PurchaseDate, price = ObjectPrice, remark = ObjectRemark)
            NewObject.save()
            # 添加新的属性
            for property in properties:
                CurrProperty = Property.objects.get(property_id=property['property_id'])
                # 创建新的ObjectProperty对象
                property_obj = ObjectProperty(
                    object=NewObject,
                    property=CurrProperty
                )
                property_obj.save()
            return JsonResponse({'id':NewObject.object_id,'message': 'Object added successfully.'}, status=200)
    except Object.DoesNotExist:
        return JsonResponse({'message': 'Object not found.'}, status=404)

# DelObject 删除物品
@api_view(['DELETE'])
@permission_classes([IsAuthenticated])
def DelObject(request):
    try:
        # 获取请求体的原始数据
        body = request.body.decode('utf-8')
        data = json.loads(body)
    except:
        return JsonResponse({'message': 'request body is required.'}, status=400)
    # 获取参数
    ObjectId = data.get('object_id') 
    try:
        if ObjectId != None:
            # 查找具有匹配 object_id 的 Object 对象
            currObject = Object.objects.get(object_id=ObjectId)
            currObject.delete()  # 删除 Object 对象
            return JsonResponse({'message': f"Object '{currObject.object_name}' deleted successfully."}, status=200)
        else:
            # 如果没有 ObjectId ，则返回错误响应
            return JsonResponse({'message': 'ObjectId is required.'}, status=400)
    except Object.DoesNotExist:
        return JsonResponse({'message': 'Object not found.'}, status=404)

# Suit 套装，获取所有套装
@api_view(['GET'])
@permission_classes([IsAuthenticated])
def GetSuits(request):
    SortID = request.GET.get('sort_id')
    try:
        sort = Sort.objects.get(sort_id=SortID)
        suits = Suit.objects.filter(sort=sort)
        suits_data = []
        for suit in suits:
            suit_data = {
                'suit_id': suit.suit_id,
                'suit_name': suit.suit_name
            }
            suits_data.append(suit_data)
        return JsonResponse({'data': suits_data}, status=200)
    except Sort.DoesNotExist:
        return JsonResponse({'message': 'Sort does not exist'}, status=404)

# Suit 套装，获取单个套装信息
@api_view(['GET'])
@permission_classes([IsAuthenticated])
def GetSuitObjects(request):
    SuitId = request.GET.get('suit_id')
    try:
        suit = Suit.objects.get(suit_id=SuitId)
        suit_data = {
            'suit_id': suit.suit_id,
            'suit_name': suit.suit_name,
            'image': suit.image.url if suit.image else None,
            'remark': suit.remark,
            'objects': []
        }
        objects = suit.suit_objects.all()
        for obj in objects:
            suit_data['objects'].append({
                'object_id': obj.object_id,
                'object_name': obj.object_name
            })
        return JsonResponse({'data': suit_data}, status=200)
    except Suit.DoesNotExist:
        return JsonResponse({'message': 'Sort does not exist'}, status=404)

# UpdateSuit 更新套装
@api_view(['POST'])
@permission_classes([IsAuthenticated])
def UpdateSuit(request):
    try:
        # 获取请求体的原始数据
        body = request.body.decode('utf-8')
        data = json.loads(body)
    except:
        return JsonResponse({'message': 'request body is required.'}, status=400)

    SortId = data.get('sort_id')  # 新增使用
    SuitName = data.get('suit_name')
    SuitId = data.get('suit_id')  # 修改使用

    try:
        if SuitId:
            # 修改套装
            suit = Suit.objects.get(suit_id=SuitId)
            suit.suit_name = SuitName
            suit.save()
        else:
            # 新增套装
            sort = Sort.objects.get(sort_id=SortId)
            suit = Suit.objects.create(sort=sort, suit_name=SuitName)
        
        # 更新套装对象
        objects_data = data.get('objects')
        if objects_data:
            suit.suit_objects.clear()  # 清空当前套装的所有对象
            for obj_data in objects_data:
                object_id = obj_data.get('object_id')
                object = Object.objects.get(object_id=object_id)
                suit.suit_objects.add(object)
        
        if SuitId:
            return JsonResponse({'message': 'Suit updated successfully'}, status=200)
        else:
            return JsonResponse({'message': 'Suit added successfully'}, status=200)
    except Sort.DoesNotExist:
        return JsonResponse({'message': 'Category does not exist'}, status=404)
    except Suit.DoesNotExist:
        return JsonResponse({'message': 'Suit does not exist'}, status=404)
    except Object.DoesNotExist:
        return JsonResponse({'message': 'Object does not exist'}, status=404)

# DelSuit 删除套装
@api_view(['DELETE'])
@permission_classes([IsAuthenticated])
def DelSuit(request):
    try:
        # 获取请求体的原始数据
        body = request.body.decode('utf-8')
        data = json.loads(body)
    except:
        return JsonResponse({'message': 'request body is required.'}, status=400)
    # 获取参数
    SuitId = data.get('suit_id') 
    try:
        if SuitId != None:
            # 查找具有匹配 suit_id 的 Suit 对象
            currSuit = Suit.objects.get(suit_id=SuitId)
            currSuit.delete()  # 删除 Suit 对象
            return JsonResponse({'message': f"Suit '{currSuit.suit_name}' deleted successfully."}, status=200)
        else:
            # 如果没有 SuitId ，则返回错误响应
            return JsonResponse({'message': 'SuitId is required.'}, status=400)
    except Suit.DoesNotExist:
        return JsonResponse({'message': 'Suit not found.'}, status=404)

# 更新图片
@api_view(['POST'])
@permission_classes([IsAuthenticated])
def UpdateImage(request):
    # 获取参数
    Id = request.POST.get('id') 
    Type = request.POST.get('type') 
    image_file = request.FILES.get('image')
    if not Type or not Id or not image_file:
        return JsonResponse({'message': 'type, id and image are required.'}, status=400)
    
    if Type=='0':
        object = Object.objects.get(object_id=Id)
        object.image = image_file
        object.save()
        return JsonResponse({'message': 'Object Image Update Successfully.'}, status=200)
    elif Type=='1':
        suit = Suit.objects.get(suit_id=Id)
        suit.image = image_file
        suit.save()
        return JsonResponse({'message': 'Suit Image Update Successfully.'}, status=200)
    return JsonResponse({'message': 'Type Error.'}, status=404)

# Record 记录，获取所有日期的记录
@api_view(['GET'])
@permission_classes([IsAuthenticated])
def GetRecords(request):
    SortID = request.GET.get('sort_id')
    try:
        sort = Sort.objects.get(sort_id=SortID)
        records = Record.objects.filter(sort=sort)
        record_data = []
        for record in records:
            record_objects = record.record_objects.all()
            objects_data = []
            for obj in record_objects:
                objects_data.append({
                    'object_id': obj.object_id,
                    'object_name': obj.object_name
                })
            
            record_entry = {
                'date': record.date,
                'objects': objects_data
            }

            if record.suit:
                suit = Suit.objects.get(suit_id=record.suit.suit_id)
                record_entry['suit_id'] = suit.suit_id
                record_entry['suit_name'] = suit.suit_name

            record_data.append(record_entry)
        
        return JsonResponse({'data': record_data}, status=200)

    except Sort.DoesNotExist:
        return JsonResponse({'message': 'Sort does not exist'}, status=404)
    except Record.DoesNotExist:
        return JsonResponse({'message': 'Record does not exist'}, status=404)

# Record 记录，获取某一天的记录
@api_view(['GET'])
@permission_classes([IsAuthenticated])
def GetDayRecord(request):
    SortID = request.GET.get('sort_id')
    date = request.GET.get('date')
    try:
        sort = Sort.objects.get(sort_id=SortID)
        record = Record.objects.get(sort=sort, date=date)

        record_objects = record.record_objects.all()
        objects_data = []
        for obj in record_objects:
            objects_data.append({
                'object_id': obj.object_id,
                'object_name': obj.object_name,
                'image': obj.image.url if obj.image else None
            })
        
        record_entry = {
            'date': record.date,
            'objects': objects_data
        }

        if record.suit:
            suit = Suit.objects.get(suit_id=record.suit.suit_id)
            record_entry['suit_id'] = suit.suit_id
            record_entry['suit_name'] = suit.suit_name
        
        return JsonResponse({'data': record_entry}, status=200)

    except Sort.DoesNotExist:
        return JsonResponse({'message': 'Sort does not exist'}, status=404)
    except Record.DoesNotExist:
        return JsonResponse({'message': 'Record does not exist'}, status=404)

# UpdateRecord 更新记录
@api_view(['POST'])
@permission_classes([IsAuthenticated])
def UpdateRecord(request):
    try:
        # 获取请求体的原始数据
        body = request.body.decode('utf-8')
        data = json.loads(body)
    except:
        return JsonResponse({'message': 'request body is required.'}, status=400)

    date = data.get('date')
    SortID = data.get('sort_id')
    objects_data = json.loads(data.get('objects'))
    SuitID = data.get('suit_id')

    try:
        sort = Sort.objects.get(sort_id=SortID)
        # 删除指定日期下的所有记录
        Record.objects.filter(date=date, sort=sort).delete()

        # 创建新的记录
        record = Record.objects.create(date=date, sort=sort)

        # 添加对象到记录
        for obj_data in objects_data:
            object_id = obj_data.get('object_id')
            object = Object.objects.get(object_id=object_id)
            record.record_objects.add(object)

        # 关联套装
        if SuitID:
            suit = Suit.objects.get(suit_id=SuitID)
            record.suit = suit
            record.save()

        return JsonResponse({'message': 'Record updated successfully.'}, status=200)

    except Object.DoesNotExist:
        return JsonResponse({'message': 'Object does not exist'}, status=404)
    except Suit.DoesNotExist:
        return JsonResponse({'message': 'Suit does not exist'}, status=404)
 
# DelRecord 删除记录
@api_view(['DELETE'])
@permission_classes([IsAuthenticated])
def DelRecord(request):
    try:
        # 获取请求体的原始数据
        body = request.body.decode('utf-8')
        data = json.loads(body)
    except:
        return JsonResponse({'message': 'request body is required.'}, status=400)

    date = data.get('date')
    SortID = data.get('sort_id')
    
    # 删除指定日期下的所有记录, sort_id=sort_id
    sort = Sort.objects.get(sort_id=SortID)
    Record.objects.filter(sort=sort, date=date).delete()

    return JsonResponse({'message': f"Record '{date}' deleted successfully."}, status=200)
    
